const mongoose = require('mongoose');

const reminderSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: [true, '用户ID不能为空']
  },
  medicineId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Medicine',
    required: [true, '药品ID不能为空']
  },
  time: {
    type: String,
    required: [true, '提醒时间不能为空'],
    validate: {
      validator: function(v) {
        return /^([01]\d|2[0-3]):([0-5]\d)$/.test(v);
      },
      message: '时间格式不正确，应为HH:mm格式'
    }
  },
  repeat: {
    type: String,
    enum: ['once', 'daily', 'weekly', 'monthly'],
    default: 'daily'
  },
  dosage: {
    type: String,
    required: [true, '服用剂量不能为空'],
    maxlength: [100, '剂量描述最多100个字符']
  },
  isActive: {
    type: Boolean,
    default: true
  },
  lastRemindedAt: {
    type: Date,
    default: null
  },
  nextRemindTime: {
    type: Date,
    required: true
  }
}, {
  timestamps: true
});

// 创建索引
reminderSchema.index({ userId: 1, medicineId: 1 });
reminderSchema.index({ nextRemindTime: 1 });
reminderSchema.index({ isActive: 1 });

// 计算下次提醒时间
reminderSchema.methods.calculateNextRemindTime = function() {
  const [hours, minutes] = this.time.split(':').map(Number);
  const now = new Date();
  let nextTime = new Date(now);
  nextTime.setHours(hours, minutes, 0, 0);

  if (nextTime <= now) {
    switch (this.repeat) {
      case 'once':
        nextTime = null;
        break;
      case 'daily':
        nextTime.setDate(nextTime.getDate() + 1);
        break;
      case 'weekly':
        nextTime.setDate(nextTime.getDate() + 7);
        break;
      case 'monthly':
        nextTime.setMonth(nextTime.getMonth() + 1);
        break;
    }
  }

  this.nextRemindTime = nextTime;
};

// 保存前计算下次提醒时间
reminderSchema.pre('save', function(next) {
  if (this.isModified('time') || this.isModified('repeat')) {
    this.calculateNextRemindTime();
  }
  next();
});

const Reminder = mongoose.model('Reminder', reminderSchema);

module.exports = Reminder;